<?php

class IndexAction extends Action {

    public function _initialize(){
        date_default_timezone_set('PRC');
        //只当日第一次登录增加登录金豆
        if($openid=cookie('token')){
            $login = $this->updatelogin($openid);
            (1==$login) && ($this->userpoints(1,$openid,1,0,1));             
        }
    }

    private function httpGet($url, $second = 30) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, $second);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
    
    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i ++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
    
        return $str;
    }
    
    private function getAccessToken($force = false) {
        $data = json_decode(file_get_contents("access_token.json"));
        if ($force || $data->expire_time < time()) {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . C('WX_APPID') . '&secret=' . C('WX_SERECT');
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 3600;
                $data->access_token = $access_token;
                $fp = fopen("access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
    
        return $access_token;
    }
    
    private function getJsApiTicket() {
        $data = json_decode(file_get_contents("jsapi_ticket.json"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen("jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }
    
        return $ticket;
    }
        
    private function getSignPackage() {
        $jsapiTicket = $this->getJsApiTicket();
        $protocol = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array("appId" => C('WX_APPID'), "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string);
        return $signPackage;
    }
    
    public function jssdk_signature() {
        $signPackage = $this->GetSignPackage();
        $this->appid = $signPackage["appId"];
        $this->nonceStr = $signPackage["nonceStr"];
        $this->timestamp = $signPackage["timestamp"];
        $this->signature = $signPackage["signature"];
    }
    
    public function debug(){        
    }
    
    public function index(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $this->major = M('Major')->select();
        $this->display();
    }

    public function indexpage(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['pubtype']=2;
        $condition['level']=1;
        if($major = I('major')){
            $condition['major']=$major;
        }
        if($key=I('key')){
            $condition['searchtext']=array('like',"%{$key}%");
        }
        $order = "pubtime desc";
        if(I('praise')==1){
            $order = "praise desc,id desc";
        }
        if(I('praise')==2){
            $order = "praise asc,id desc";
        }
        $list = M('MedicalRecords')->where($condition)->order($order)->limit($limit)->select();
        //echo M('MedicalRecords')->getLastSql();
        $this->ajaxReturn($list,"JSON");        
        
    }

    public function bl_info(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $condition['id']=I('id');
        M('MedicalRecords')->where($condition['id'])->setInc('viewnums');//增加查看数
        $this->reportData("visit",1,$condition['id']);
        $this->record = $record = M('MedicalRecords')->where($condition)->find();
        $this->userinfo = $user = M('User')->where("id='{$record['user_id']}'")->find();
        $this->headimg = ($user['image']?$user['image']:$user['headimgurl']);
        $this->image = M('MedicalRecordsImages')->where("rec_id={$condition['id']}")->select();
        //echo M('MedicalRecordsImages')->getLastSql();
        if($record['age']){
            $this->age=M('MedicalRecordsAge')->where("id={$record['age']}")->getField('age');
            //echo M('MedicalRecordsAge')->getLastSql();
        }
        $praise = M('MedicalRecordsPraise')->where("user_id={$user['id']} and rec_id={$condition['id']}")->find();
        //echo M('MedicalRecordsPraise')->getLastSql();
        if($praise){
            $this->praise = 0; //不能点
        }else{
            $this->praise = 1; //可以点
        }
        $this->display();
    }

    public function bl_info_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $openid = cookie('token');
        $pageSize=I('pageSize');
        $pageIndex=I('pageIndex');
        $rec_id = I('id');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $list = D('DiscussView')->where("rec_id={$rec_id} and pubtype<>3 and (pubtype=1 or (MedicalRecordsDiscuss.openid='{$openid}' and pubtype=2))")->order('cashtype desc')->limit($limit)->select();
        //echo D('DiscussView')->getLastSql();
        foreach ($list as $key => $value) {
            if($value['user_id']==$userid){
                $list[$key]['display']=1;//全部展示
            }else{
                if($value['pubtype']==2){
                    $list[$key]['display']=0;//不是自己的，不公开的，不显示
                }
            }
            $list[$key]['headimg']=($value['image']?$value['image']:$value['headimgurl']);
            if($value['cashtype']!=3){
                $list[$key]['distime']=date('Y.m.d',$value['distime']);
            }
        }
        $this->ajaxReturn($list,"JSON");
    }

    public function bl_info_praise(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $rec_id=I('id');
        $token = md5($userid."|".$rec_id);
        $addtime = time();
        $sql = "INSERT INTO `box_medical_records_praise`(`rec_id`, `user_id`, `token`) VALUES ({$rec_id},{$userid},'{$token}') ON DUPLICATE KEY UPDATE `addtime`= '{$addtime}';";
        M()->query($sql);
        //echo M()->getLastSql();
        $res = mysql_affected_rows();
        if($res==1){
            M('MedicalRecords')->where("id={$rec_id}")->setInc('praise');
            $this->reportData("praise",1,$rec_id);
            $json['status']=1;
        }else{
            $json['status']=0;
            $json['msg']='已经点过赞';
        }
        $this->ajaxReturn($json,"JSON");
    }

    public function bl_info_discuss(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $openid = cookie('token');
        $level = M('User')->where("id={$userid}")->getField('level');
        if(1==$level){
            $this->ajaxReturn(array('status'=>2,'msg'=>'请先升级为医生'),"JSON");
            exit;
        }        
        if(IS_POST){
            $data['user_id']=$userid;
            $data['rec_id']=I('id');
            $data['content']=I('content');
            $data['addtime']=$data['distime']=time();
            $add = M('MedicalRecordsDiscuss')->add($data);
            if($add){
                M('MedicalRecords')->where("id={$data['rec_id']}")->setInc('discussnums');
                $this->reportData("discuss",1,$data['rec_id']);
                $discuss = $this->updatediscuss($openid);
                //只当日第一次评论增加登录金豆
                (1==$discuss) && ($this->userpoints(12,$openid,1,0)); 
                $json['status']=1;
                 $json['msg']='评论成功';
            }else{
                $json['status']=0;
                $json['msg']='评论失败';
            }
            $this->ajaxReturn($json,"JSON");
        }        
    }

    public function fbbl(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $level = M('User')->where("id={$userid}")->getField('level');
        if(1==$level){
            $this->show('<script>alert("请先升级为医生");window.location="'.U('Index/up_doctor').'"</script>');
            exit;
        }
        if($level>2){
            $this->redirect('Index/xjbl');//跳转到专家发布病例
        }

        if(IS_POST){
            $data['user_id']=$userid;
            $data['cashtype']=1;
            $data['pubtype']=I('pubtype');
            $data['gender']=I('gender');
            $data['age']=intval(I('age'));
            $data['major']=I('major');
            $data['complain']=I('complain');
            $data['history']=I('history');
            $data['oralhistory']=I('oralhistory');
            $data['profile']=I('profile');
            $data['normalcheck']=I('normalcheck');
            $data['specialcheck']=I('specialcheck');
            $data['diagnostic']=I('diagnostic');
            $data['tp']=I('tp');
            $data['rediagnosis']=I('rediagnosis');
            $data['prognosis']=I('prognosis');
            $data['discuss']=I('discuss');
            $searchtext = implode(" ",$data);
            $data['searchtext']=$searchtext;
            $data['level']=1;
            $data['savetime']=$data['addtime']=time();
            if($data['pubtype']==2){
                $data['pubtime']=time();
            }
            if($image = I('images')){
                $data['image'] = "./Public/static/is_pic.jpg";
            }else{
                $data['image'] = "./Public/static/no_pic.jpg";
            }
            $add = M('MedicalRecords')->add($data);
            if($add){
                $openid=cookie('token');
                $this->userpoints(11,$openid,1,0);
                if($image = I('images')){
                    $images = explode(",",$image);
                    for($i=0;$i<count($images);$i++){
                        $medrecord['image']=$this->saveMedia($images[$i]);
                        if($i==0){
                            M('MedicalRecords')->where("id={$add}")->save(array('image'=> $medrecord['image']));
                        }
                        $medrecord['rec_id']=$add;
                        M('MedicalRecordsImages')->add($medrecord);
                    }
                }
                $this->ajaxReturn(array('status'=>1, 'rec_id'=>$add),"JSON");exit;
            }else{
                $this->ajaxReturn(array('status'=>0),"JSON");exit;
            }                             
        }

        $this->age = M('MedicalRecordsAge')->select();
        $this->major =M('Major')->select();
        $this->display();
    }

    public function yqzj(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $this->rec_id=I('rec_id');
        $this->area = M('Area')->select();
        $this->department = M('Department')->select();
        $this->points = M('User')->where("openid='".cookie('token')."'")->getField('points');
        $this->display();
    }

    public function yqzj_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $openid = cookie('token');
        $pageSize=I('pageSize');
        $pageIndex=I('pageIndex');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['status'] = 1;
        $condition['level'] = array('gt',2);
        if($department = I('department')){
            $condition['department'] = $department;
        }
        if($area = I('area')){
            $condition['doctorprovince'] = $area;
        }
        if($key = I('key')){
            $condition['searchtext'] = array('like',"%{$key}%");
        }
        $order = "id desc";
        if(I('praise') == 1){
            $order = "praise desc,id desc";
        }
        if(I('praise') == 2){
            $order = "praise asc,id desc";
        }

        $list = D('ExpertView')->where($condition)->order($order)->limit($limit)->select();
        
        foreach ($list as $key => $value) {
            $list[$key]['headimg']=($value['image']?$value['image']:$value['headimgurl']);
        }

        $this->ajaxReturn($list,"JSON");

    }

    public function yqzj_info(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $condition['id']=I('id');
        $list = D('ExpertView')->where($condition)->find();
        $list['headimg']=($list['image']?$list['image']:$list['headimgurl']);
        $this->expert = $list;
        $this->display();
    }

    public function zjbl(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->department = M('Department')->select();
        $this->area = M('Area')->select();
        $this->display();
    }

    public function zjbl_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $openid = cookie('token');
        $pageSize=I('pageSize');
        $pageIndex=I('pageIndex');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['status']=1;
        $condition['level']=array('gt',2);
        if($department = I('department')){
            $condition['department']=$department;
        }
        if($area = I('area')){
            $condition['doctorprovince']=$area;
        }
        if($key=I('key')){
            $condition['searchtext']=array('like',"%{$key}%");
        }
        $order = "id desc";
        if(I('praise')==1){
            $order = "praise desc,id desc";
        }
        if(I('praise')==2){
            $order = "praise asc,id desc";
        }

        $list = D('ExpertView')->where($condition)->order($order)->limit($limit)->select();

        foreach ($list as $key => $value) {
            $list[$key]['headimg']=($value['image']?$value['image']:$value['headimgurl']);
        }

        $this->ajaxReturn($list,"JSON");        
    }

    public function bl_list(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->major = M('Major')->select();
        $this->display();        
    }

    public function bl_list_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');

        $limit = $pageIndex*$pageSize.",".$pageSize;

        $condition['pubtype']=2;//发布
        $condition['level']=2;//专家
        $condition['cashtype']=1;//免费
        if($major = I('major')){
            $condition['major']=$major;
        }
        if($key=I('key')){
            $condition['searchtext']=array('like',"%{$key}%");
            $condition['cashtype']=array('neq',0);//搜索的时候免费收费的都可以搜索到
        }
        $order = "pubtime desc";
        if(I('praise')==1){
            $order = "praise desc,id desc";
        }
        if(I('praise')==2){
            $order = "praise asc,id desc";
        }
        $list = D('BlistView')->where($condition)->order($order)->limit($limit)->select();
        foreach ($list as $key => $value) {
            $list[$key]['headimg']=($value['image']?$value['image']:$value['headimgurl']);
        }
        $this->ajaxReturn($list,"JSON");                
    }

    public function xjbl(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $level = M('User')->where("id={$userid}")->getField('level');
        if(1==$level){
            $this->show('<script>alert("请先升级为医生");window.location="'.U('Index/up_doctor').'"</script>');
            exit;
        }
        if($level<3){
            $this->redirect('Index/fbbl');//跳转到医生发布病例
        }
        if(IS_POST){
            $data['user_id']=$userid;
            $data['level']=2;
            
            if($cashtype=I('cashtype')){
                $data['cashtype']=$cashtype;
            }else{
                  $data['cashtype']=1;
            }
            $data['pubtype']=I('pubtype');
            $data['gender']=I('gender');
            $data['age']=intval(I('age'));
            $data['major']=I('major');
            $data['complain']=I('complain');
            $data['history']=I('history');
            $data['oralhistory']=I('oralhistory');
            $data['profile']=I('profile');
            $data['normalcheck']=I('normalcheck');
            $data['specialcheck']=I('specialcheck');
            $data['diagnostic']=I('diagnostic');
            $data['tp']=I('tp');
            $data['rediagnosis']=I('rediagnosis');
            $data['prognosis']=I('prognosis');
            $data['discuss']=I('discuss');
            $searchtext = implode(" ",$data);
            $data['searchtext']=$searchtext;
            //$data['level']=1;
            $data['savetime']=$data['addtime']=time();
            $isSave = 0;
            if(($data['pubtype']==2) && ($data['cashtype']==2)){
                //这里需要判断发布的收费病例数是否大于4份
                $getThisMonth = $this->getThisMonth();
                $condition['pubtime'] = array('between',array($getThisMonth['substime'],$getThisMonth['subetime']));
                $condition['cashtype']=2;//收费
                $condition['pubtype']=2;//发布
                $condition['user_id']=$userid;
                $countlimit = M('MedicalRecords')->where($condition)->count();//不能大于4

                if($countlimit<4){
                    $data['pubtime']=time();
                    $this->updateExpertPub($userid);//插入到专家发布的列表
                }else{
                    $data['pubtype']=1;//存草稿
                    $isSave = 1;
                }
            }
            if($image = I('images')){
                $data['image'] = "./Public/static/is_pic.jpg";
            }else{
                $data['image'] = "./Public/static/no_pic.jpg";
            }
            $add = M('MedicalRecords')->add($data);
            if($add){
                $openid = cookie('token');
                $this->userpoints(11,$openid,1,0);
                if($image = I('images')){
                    $images = explode(",",$image);
                    for($i=0;$i<count($images);$i++){
                        $medrecord['image']=$this->saveMedia($images[$i]);
                        if($i==0){
                            M('MedicalRecords')->where("id={$add}")->save(array('image'=>$medrecord['image']));
                        }
                        $medrecord['rec_id']=$add;
                        M('MedicalRecordsImages')->add($medrecord);
                    }
                }
                if($isSave==1){
                    $this->ajaxReturn(array('status'=>2),"JSON");exit; //本月已发布的收费病例数大于4份，
               }else{
                    //存入每订阅人的病例表
                    $sub['a.item_id']=$userid;
                    $sub['b.status']=2;         //支付成功
                    $sub['b.paytype']=2;        //订阅
                    $sub['a.substime']=array("egt",$data['pubtime']);
                    $sub['a.subetime']=array("lt",$data['pubtime']);
                    $list = M()->Table('box_user_order_detail a')->join('box_user_order b on a.order_num = b.order_num')->where($sub)->field('b.openid')->select();
                    foreach ($list as $key => $value) {
                        $addtime=time();
                        $token = md5($value['openid']."|".$add);
                        $sql = "INSERT INTO `box_user_records`(`openid`, `rec_id`, `expert_id`, `token`, `addtime`) 
                                            VALUES ('{$value['openid']}',{$add},{$userid},'{$token}',{$addtime})
                                            ON DUPLICATE KEY UPDATE `addtime`={$addtime}";
                        M()->query($sql);
                    }
                    //
                    $this->ajaxReturn(array('status'=>1),"JSON");exit; 
               }
                
            }else{
                $this->ajaxReturn(array('status'=>0),"JSON");exit;
            }                             
        }

        $this->age = M('MedicalRecordsAge')->select();
        $this->major =M('Major')->select();
        $this->display();    
    }

    public function yqzj_info2(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $this->points = M('User')->where("openid='".cookie('token')."'")->getField('points');
        $id = I('id');//医生ID
        $user =  M('User')->where("id='{$id}'")->find();
        $user['headimg']=($user['image']?$user['image']:$user['headimgurl']);
        $this->userinfo = $user;
        $levelprice = M('UserLevel')->where("id={$user['level']}")->field('recordprice,subprice')->find();
        $this->recordprice = $levelprice['recordprice'];
        $this->subprice = $levelprice['subprice'];
        $this->display();        
    }

    public function yqzj_info2_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $user_id =I('userid');
        $level = M('User')->where("id={$user_id}")->getField('level');
        $recordprice = M('UserLevel')->where("id={$level}")->getField('recordprice');
        //echo M('UserLevel')->getLastSql();
        $openid = cookie('token'); 
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;

        $condition['pubtype']=2;//发布的
        //$condition['cashtype']=2;//收费的
        $condition['user_id']=$user_id;
        $order="pubtime desc";
        $list = D('BlistView')->where($condition)->order($order)->limit($limit)->select();
        foreach ($list as $key => $value) { 
            $list[$key]['recordprice']=$recordprice;
            $detail['openid']=$openid;
            $detail['rec_id']=$value['rec_id'];
            $isBuy = M('UserRecords')->where($detail)->getField('id');
           //echo  M('UserRecords')->getLastSql();
            if($isBuy){
                $list[$key]['isBuy']=1;
            }else{
                $list[$key]['isBuy']=0;
            }
        }
        $this->ajaxReturn($list,"JSON");
    }

    public function dyzf(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $condition['id']=I('userid');
        $user= M('User')->where($condition)->find();
        $user['headimg']=($user['image']?$user['image']:$user['headimgurl']);
        $this->userinfo=$user;
        $this->display();        
    }

    public function zf(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->rec_id = I('rec_id');
        $this->display();        
    }

    public function zf2(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->userid= I('userid');
        $this->display();        
    }

    public function oral_circle(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;

        $this->major = M('Major')->select();
        $this->area = M('Area')->select();

        $this->display();        
    }

    public function oral_circle_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize'); 
        $limit = $pageIndex*$pageSize.",".$pageSize;

        $condition['pubtype']=2;//发布的

        if($major = I('major')){
            $condition['major']=$major;
        }
        if($key=I('key')){
            $condition['searchtext']=array('like',"%{$key}%");
        }

        if($area = I('area')){
            $condition['location']=$area;
        }

        $list = M('Event')->where($condition)->order('id desc')->limit($limit)->select();
        foreach ($list as $key => $value) {
            if(($value['restnums'])==0){
                $list[$key]['state']=3;//报名已满
            }else{
                $list[$key]['state']=2;//可以报名
            }
            if(strtotime($value['starttime'])<time()){
                $list[$key]['state']=1;//报名已结束
            }
            if(strtotime($value['endtime'])<time()){
                $list[$key]['state']=4;//活动已结束
            }            
        }
        $this->ajaxReturn($list,"JSON");
    }

    public function actity_wfb_edit(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $level = M('User')->where("id={$userid}")->getField('level');
        if(1==$level){
            $this->show('<script>alert("请先升级为医生");window.location="'.U('Index/up_doctor').'"</script>');
            exit;
        }
        if(IS_POST){
            $data['user_id']=$userid;
            $data['cashtype']=intval(I('cashtype'));
            $data['isonline']=I('isonline');
            $data['eventlink']=I('eventlink');
            $data['location']=I('location');
            $data['price']=I('price');
            $data['name']=I('name');
            $data['pubtype']=I('pubtype');
            $data['period']=I('period');
            $data['starttime']=I('starttime');
            $data['endtime']=I('endtime');
            $data['major']=I('major');
            $data['partitions']=I('partitions');
            $data['membercount']=I('membercount');
            $data['conditions']=I('conditions');
            $data['description']=I('description');
            $data['schedule']=I('schedule');
            $data['traffic']=I('traffic');
            $data['tips']=I('tips');
            $data['restnums']=$data['membercount'];
            $searchtext = implode(" ",$data);
            $data['searchtext']=$searchtext;
            $data['savetime']=$data['addtime']=time();
            $add = M('Event')->add($data);
            if($add){
                if($image = I('images')){
                    //$data['image'] = "./Public/static/is_pic.jpg";
                    $images = explode(",",$image);
                    for($i=0;$i<count($images);$i++){
                        $event['image']=$this->saveMedia($images[$i]);
                        if($i==0){
                            M('Event')->where("id={$add}")->save(array('image'=>$event['image']));
                        }
                        $event['event_id']=$add;
                        M('EventImages')->add($event);              
                    }
                }else{
                    $data['image'] = "./Public/static/no_pic.jpg";
                }
                if($organizer=I('organizers')){
                    $organizers = explode(",",$organizer);
                    for($i=0;$i<count($organizers);$i++){
                        $eventorg['name']=$organizers[$i];
                        $eventorg['event_id']=$add;
                        M('EventOrganizer')->add($eventorg);                
                    }               
                }
                if($contact=I('contacts')){
                    $contacts = explode(",",$contact);
                    for($i=0;$i<count($contacts)/3;$i++){
                        $eventcont['name']=$contacts[i*3+0];
                        $eventcont['mobile']=$contacts[i*3+1];
                        $eventcont['email']=$contacts[i*3+2];
                        $eventcont['event_id']=$add;
                        M('EventContact')->add($eventcont);
                        
                    }               
                }           
                $this->ajaxReturn(array('status'=>1),"JSON");exit;
            }else{
                $this->ajaxReturn(array('status'=>0),"JSON");exit;
            }
        }
        $this->area = M('Area')->select();
        $this->major = M('Major')->select();
        $this->display();
    }

    public function actity_info(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $openid=cookie('token');
        $condition['id']=I('id');
        M('Event')->where($condition['id'])->setInc('viewnums');//增加查看数
        $this->reportData("visit",2,$condition['id']);
        $this->event = $event =  M('Event')->where($condition)->order('id desc')->find();
        $this->image = M('EventImages')->where("event_id={$condition['id']}")->select();
        $this->org = M('EventOrganizer')->where("event_id={$condition['id']}")->select();
        $this->contact = M('EventContact')->where("event_id={$condition['id']}")->select();
        $this->order_num = $order_num = M('UserOrderDetail')->where("item_id='{$condition['id']}' and openid='{$openid}'")->getField('order_num');
        
        if(strtotime($event['endtime'])<time()){
            $this->reg = 7;//活动已结束
        }elseif(strtotime($event['starttime'])<time()){
            $this->reg = 5;//报名已结束
        }else{
            $registration= M('EventRegistration')->where("openid='{$openid}' and event_id={$condition['id']}")->find();
            if ($registration) {
                $isallpoint = $registration['isallpoint'];
                if($event['price']==0){
                    $this->reg =4;//免费退出报名
                } else {
                    if($isallpoint==2){
                        $this->reg=3;//等额抵扣金豆退款
                    } elseif($isallpoint==1){
                        $this->reg=2;//现金金豆退款
                    }
                }
            } else {
                if($event['restnums']==0){
                    $this->reg = 6;//名额已满
                }else{
                    $this->reg=1;//我要参加
                }
            }
        }

        $this->display();
    }

    public function actity_info_praise(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $rec_id=I('id');
        $token = md5($userid."|".$rec_id);
        $addtime = time();
        $sql = "INSERT INTO `box_event_praise`(`rec_id`, `user_id`, `token`) VALUES ({$rec_id},{$userid},'{$token}') ON DUPLICATE KEY UPDATE `addtime`= '{$addtime}';";
        M()->query($sql);
        //echo M()->getLastSql();
        $res = mysql_affected_rows();
        if($res==1){
            M('Event')->where("id={$rec_id}")->setInc('praise');
            $this->reportData("praise",2,$rec_id);
            $json['status']=1;
        }else{
            $json['status']=0;
            $json['msg']='已经点过赞';
        }
        $this->ajaxReturn($json,"JSON");
    }

    public function actity_join(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $condition['id']=I('id');
        if(IS_POST){
            $restnums = M('Event')->where($condition)->getField('restnums');
            if( $restnums > 0 ){
                $data['openid']=cookie('token');
                $data['name']=I('name');
                $data['mobile']=I('mobile');
                $data['hospital']=I('hospital');
                $data['department']=I('department');
                $data['event_id']=I('id');
                M('EventRegistration')->add($data);
                M('Event')->where($condition)->setDec('restnums');
                $json['status']=1;
            }else{
                $json['status']=0;
                $json['msg']='已超过报名限制人数';
            }

            $this->ajaxReturn($json,"JSON");
            exit;
        } 
        
        $condition['id']=I('id');
        $this->event = $event =  M('Event')->where($condition)->find();
        $this->org = M('EventOrganizer')->where("event_id={$condition['id']}")->select();
        $this->userinfo = $user = M('User')->where("id={$userid}")->field('name,mobile,hospital,department,points')->find();
        $this->points = $user['points'];
        $this->display('Index/join');
    } 


    public function actity_free_refund(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $condition['event_id']=I('id');
        $condition['openid']=cookie('token');
        $del = M('EventRegistration')->where($condition)->delete();
        if($del){
            $json['status']=1;
            M('Event')->where("id={$condition['event_id']}")->setInc('restnums');
        }else{
            $json['status']=0;
            $json['msg']='退出报名失败';
        }

        $this->ajaxReturn($json,"JSON");
    }

    public function actity_refund(){//现金退款
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $condition['order_num']=I('order_num');
        $detail = M('UserOrderDetail')->where($condition)->find();
        $refund = $this->event_refund($detail['transaction_id'],$condition['order_num'],$detail['return_num'],$detail['fee']);
        if(!$refund){
            $json['status']=0;
            $json['msg']='退款失败';
        }else{
            $openid = cookie('token');
            $this->userpoints(90,$openid,1,$detail['points'],1,$condition['order_num']);
            $this->userpoints(80,$openid,2,$detail['fee']/100,1,$condition['order_num']);
            M('UserOrderDetail')->where($condition)->delete();
            M('UserOrder')->where($condition)->delete();
            $nums = M('UserOrderDetail')->where($condition)->getField('nums');
            M('Event')->where("id={$detail['item_id']}")->setInc('restnums',$nums);
            M('EventRegistration')->where("openid='{$openid}' and event_id={$detail['item_id']}")->delete();//删除报名信息
            $json['status']=1;
        }
        $this->ajaxReturn($json,"JSON");
    }

    private function event_refund($transaction_id,$out_trade_no,$return_num,$totalfee){
        $param['appid']=C('WX_APPID');//APPID 
        $param['mch_id']=C('WX_MCHID');//商户号
        $param['nonce_str']=$this->nonceStr;//随机数
        $param['transaction_id']=$transaction_id;//微信订单号
        $param['out_trade_no']=$out_trade_no;//商户系统内部的订单号
        $param['out_refund_no']=$return_num;
        $param['total_fee']=$totalfee;//
        $param['refund_fee']=$totalfee;
        $param['op_user_id']=C('WX_MCHID');
        $param['sign'] = $this->wxpaySign($param);//支付签名
        $data = $this->wxRefundXML($param);
        if($response = $this->postXmlCurl($data)){
            $xml = (array) simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA);//XML转数组，还要再验证一次签名
            if( ($xml['return_code']=="SUCCESS") && ($xml['result_code']=="SUCCESS")){
                $wxPrepaySign = $xml['sign'];
                //去除返回的签名
                unset($xml['sign']);
                if($wxPrepaySign==$this->wxpaySign($xml)){
                    $data['refund_id']=$xml['refund_id'];
                    $data['returntime']=time();
                    $data['status']=3;
                    M('UserOrderDetail')->where("order_num='{$out_trade_no}'")->save($data);
                    return 1;
                }else{
                    return 0;
                }
            }elseif($xml['err_code']=='SYSTEMERROR'){       //微信支付其实也会抽风的
                return 0;
            }else{
                return 0;
            }
        }else{
            return 0;
        }


    }

    public function actity_info_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['event_id']=I('eventid');
        $condition['pubtype']=1;
        $list = D('ElistView')->where($condition)->order("addtime desc")->limit($limit)->select();
        foreach ($list as $key => $value) {
           $list[$key]['headimg']=($value['image']?$value['image']:$value['headimgurl']);
           $list[$key]['addtime']=date('Y.m.d',$value['addtime']);
        }
        $this->ajaxReturn($list,"JSON");
    }

    public function actity_info_discuss(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $openid = cookie('token');
        $level = M('User')->where("id={$userid}")->getField('level');
        if(1==$level){
            $this->ajaxReturn(array('status'=>2,'msg'=>'请先升级为医生'),"JSON");
            exit;
        }        
        if(IS_POST){
            $data['user_id']=$userid;
            $data['event_id']=I('id');
            $data['content']=I('content');
            $data['addtime']=time();
            $add = M('EventDiscuss')->add($data);
            if($add){
                M('Event')->where("id={$data['event_id']}")->setInc('discussnums');
                $this->reportData("discuss",2,$data['event_id']);
                $json['status']=1;
                $json['msg']='评论成功';
            }else{
                $json['status']=0;
                $json['msg']='评论失败';
            }
            $this->ajaxReturn($json,"JSON");
        }        
    }


    public function navright(){
        $this->user = $user=M('User')->where("openid='".cookie('token')."'")->find();
        !$user && $this->snsauth() && exit;
        $this->headimg = ($user['image']?$user['image']:$user['headimgurl']);
        //level 1未升级 2普通以上 3专家医生
        $this->level = $user['level'];
        $this->display();
    } 

    public function up_doctor(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $level = M('User')->where("id={$userid}")->getField('level');
        if($level > 1){
            $json['status']=0;
            $json['msg']="你已经升级为医生了";
            $this->ajaxReturn($json,"JSON");            
            exit;
        }
        
        if(IS_POST){
            $smscode = I('smscode');
            if($smscode!=session('smscode')){
                $json['status']=0;
                $json['msg']="短信验证码不正确";
                $this->ajaxReturn($json,"JSON");exit;
            }
            $data['name']=I('name');
            $data['hospital']=I('hospital');
            $data['department']=I('department');
            $data['position']=I('position');
            $data['socialposition']=I('socialposition');
            $data['mobile']=I('mobile');
            //$data['level']=2;
            $condition['id']=$userid;
            $save = M("User")->where($condition)->save($data);
            if($save!==false){
                $openid=cookie('token');
                $this->userpoints(10,$openid,1,0,1);//增加金豆
                M('User')->where("id={$userid}")->save(array("level"=>2));   
                $json['status']=1;
                $json['msg']="升级用户成功"; 
            }else{
                $json['status']=0;
                $json['msg']="升级用户失败";
            }

            $this->ajaxReturn($json,"JSON");exit;

        }
        $this->department = M('Department')->select();
        $this->display();
    }

    public function person_info(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->userinfo = $user =  M('User')->where("id='{$userid}'")->find();
        $this->headimg = ($user['image']?$user['image']:$user['headimgurl']);
        $this->display();
    }

    public function person_info4_edit(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        if(IS_POST){
            $data['name']=I('name');
            $data['hospital']=I('hospital');
            $data['department']=I('department');
            $data['position']=I('position');
            $data['socialposition']=I('socialposition');
            $data['mobile']=I('mobile');
            $data['resume']=I('resume');
            $data['email']=I('email');
            //$data['level']=2;
            $condition['id']=$userid;
            $save = M('User')->where($condition)->save($data);
            if($save !== false){
                $json['status']=1;
                $json['msg']="个人信息保存成功";
            }else{
                $json['status']=0;
                $json['msg']="个人信息保存失败";
            }

            $this->ajaxReturn($json,"JSON");exit;
        }
        $this->userinfo = M('User')->where("id='{$userid}'")->find();
        
        $this->department = M('Department')->select();
        $this->display();
    }

    public function person_info3(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->userinfo = $user =  M('User')->where("id='{$userid}'")->find();
        $this->headimg = ($user['image']?$user['image']:$user['headimgurl']);
        $this->level = M('UserLevel')->where("id={$user['level']}")->find();
        $this->display();        
    }

    public function my_bl(){//我的病历 未发布
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->display();        
    }

    public function my_bl_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $order = "pubtime desc";
        $condition['pubtype']=1;//草稿
        $condition['user_id']=$userid;
        $list = M('MedicalRecords')->where($condition)->order($order)->limit($limit)->select();
        $this->ajaxReturn($list,"JSON");        
    }

    public function bl_edit(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $this->level = $level = M('User')->where("id={$userid}")->getField('level');
        if(IS_POST){
            $condition['id']=I('id');
            $data['user_id']=$userid;
            $data['level']=($level>1)?2:1;
            if($cashtype=I('cashtype')){
                $data['cashtype'] = $cashtype;
            }else{
                $data['cashtype']=1;
            }
            $data['pubtype']=I('pubtype');
            $data['gender']=I('gender');
            $data['age']=intval(I('age'));
            $data['major']=I('major');
            $data['complain']=I('complain');
            $data['history']=I('history');
            $data['oralhistory']=I('oralhistory');
            $data['profile']=I('profile');
            $data['normalcheck']=I('normalcheck');
            $data['specialcheck']=I('specialcheck');
            $data['diagnostic']=I('diagnostic');
            $data['tp']=I('tp');
            $data['rediagnosis']=I('rediagnosis');
            $data['prognosis']=I('prognosis');
            $data['discuss']=I('discuss');
            $searchtext = implode(" ",$data);
            $data['searchtext']=$searchtext;
            //$data['level']=1;
            $data['savetime']=time();
            $isSave = 0;
            if(($data['pubtype']==2) && ($data['cashtype']==2)){
                //这里需要判断发布的收费病例数是否大于4份
                $getThisMonth = $this->getThisMonth();
                $where['pubtime'] = array('between',array($getThisMonth['substime'],$getThisMonth['subetime']));
                $where['cashtype']=2;//收费
                $where['pubtype']=2;//发布
                $where['user_id']=$userid;
                $countlimit = M('MedicalRecords')->where($where)->count();//不能大于4

                file_put_contents("/var/www/html/log.lg",M('MedicalRecords')->getLastSql());
                if($countlimit<4){
                    $data['pubtime']=time();
                    $this->updateExpertPub($userid);//插入到专家发布的列表
                }else{
                    $data['pubtype']=1;//存草稿
                    $isSave = 1;
                }
            }
            // if($image = I('images')){
            //     $data['image'] = "./Public/static/is_pic.jpg";
            // }else{
            //     $data['image'] = "./Public/static/no_pic.jpg";
            // }
            $save = M('MedicalRecords')->where($condition)->save($data);
            if($save!==false){
                //$this->userpoints(11,$openid,1,0);
                if($image = I('images')){
                    $images = explode(",",$image);
                    for($i=0;$i<count($images);$i++){
                        if($i==0){
                             M('MedicalRecords')->where("id={$condition['id']}")->save(array('image'=>$images[$i]));
                        }
                        $medrecord['image']=$images[$i];
                        $medrecord['rec_id']=$condition['id'];
                        M('MedicalRecordsImages')->add($medrecord);
                    }
                }else{
                   M('MedicalRecords')->where("id={$condition['id']}")->save(array('image'=>'./Public/static/no_pic.jpg'));
                }

                if($isSave==1){
                    $this->ajaxReturn(array('status'=>2),"JSON");exit; //本月已发布的收费病例数大于4份，
               }else{

                    if(($data['level']==2) &&($data['cashtype']==2)){
                            $sub['a.item_id']=$userid;
                            $sub['b.status']=2;//支付成功
                            $sub['b.paytype']=2;//订阅
                            $sub['a.substime']=array("egt",$data['pubtime']);
                            $sub['a.subetime']=array("lt",$data['pubtime']);
                            $list = M()->Table('box_user_order_detail a')->join('box_user_order b on a.order_num = b.order_num')->where($sub)->field('b.openid')->select();
                            foreach ($list as $key => $value) {
                                $addtime=time();
                                $token = md5($value['openid']."|".$addtime);
                                $sql = "INSERT INTO `box_user_records`(`openid`, `rec_id`, `expert_id`, `token`, `addtime`) 
                                                    VALUES ('{$value['openid']}',{$condition['id']},{$userid},'{$token}',{$addtime})
                                                    ON DUPLICATE KEY UPDATE `addtime`={$addtime}";
                                M()->query($sql);
                            }
                    }
                    //存入每订阅人的病例表

                    //
                    $this->ajaxReturn(array('status'=>1),"JSON");exit; 
               }                
                //$this->ajaxReturn(array('status'=>1),"JSON");exit;
            }else{
                $this->ajaxReturn(array('status'=>0),"JSON");exit;
            }                             
        }
        $condition['id']=I('id'); 
        $this->record = $record = M('MedicalRecords')->where($condition)->find();
        $this->images = M('MedicalRecordsImages')->where("rec_id={$condition['id']}")->select(); 
        $this->age = M('MedicalRecordsAge')->select();
        $this->age1 = M('MedicalRecordsAge')->where("id={$record['age']}")->getField('age');
        $this->major =M('Major')->select();
        $this->display();     
    }

    public function bl_delete(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $condition['id']=I('id');
        $condition['user_id']=$userid;
        $del = M('MedicalRecords')->where($condition)->delete();  
        if($del){
            M('MedicalRecordsImages')->where("rec_id={$condition['rec_id']}")->delete();
            $this->ajaxReturn(array('status'=>1),"JSON");
        }else{
            $this->ajaxReturn(array('status'=>1,'msg'=>'删除失败'),"JSON");
        }      
    }

    public function my_already_fb(){//我的病历 已发布
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->display();  
    }

    public function my_already_fb_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $order = "savetime desc";
        $condition['pubtype']=2;//已发布
        $condition['user_id']=$userid;
        $list = M('MedicalRecords')->where($condition)->order($order)->limit($limit)->select();
        $this->ajaxReturn($list,"JSON");          
    }

    public function my_dg(){//我的订购 购买的病历
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->display();               
    }

    public function my_dg_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['openid']=cookie('token');
        $list = D('RlistView')->where($condition)->group("expert_id")->limit($limit)->select(); 
        foreach ($list as $key => $value) {
            $list[$key]['headimg']=($value['image']?$value['image']:$value['headimgurl']);
        }
        $this->ajaxReturn($list,"JSON");      
    }

    public function myDg_info(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->expert_id = I('expert_id');
        $this->display();    
    }

    public function myDg_info_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['a.openid']=cookie('token');
        $condition['expert_id']=I('expert_id');
        $list = M()->Table('box_user_records a')->join('box_medical_records b on a.rec_id=b.id')->field('b.*')->where($condition)->limit($limit)->order('a.addtime desc')->select();
        $this->ajaxReturn($list,"JSON");                 
    }

    public function dpjl(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->level = M('User')->where("id={$userid}")->getField('level');
        $this->display();        
    }

    public function dpjl_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['pubtype']=array('neq',3);
        $condition['cashtype']=I('cashtype');//3待评论2已评论
        $condition['openid']=cookie('token');
        $list = D('WlistView')->where($condition)->order('addtime desc')->group('rec_id')->limit($limit)->select();
        $this->ajaxReturn($list,"JSON");
    }

    public function dpjl1(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->display();        
    }

    public function dpjl1_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['pubtype']=array('neq',3);
        $condition['cashtype']=I('cashtype');//3待评论2已评论
        $condition['user_id']=$userid;
        $list = D('WlistView')->where($condition)->order('addtime desc')->limit($limit)->select();
        //echo D('WlistView')->getlastSql();
        $this->ajaxReturn($list,"JSON");
    }

    public function bl_info3(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $discuss['id']=$this->id = I('id');
        $condition['id'] = M('MedicalRecordsDiscuss')->where($discuss)->getField('rec_id');
        $this->record = $record = M('MedicalRecords')->where($condition)->find();
        $this->userinfo = $user = M('User')->where("id='{$record['user_id']}'")->find();
        $this->headimg = ($user['image']?$user['image']:$user['headimgurl']);
        $this->image = M('MedicalRecordsImages')->where("rec_id={$condition['id']}")->select();
        //echo M('MedicalRecordsImages')->getLastSql();
        if($record['age']){
            $this->age=M('MedicalRecordsAge')->where("id={$record['age']}")->getField('age');
            //echo M('MedicalRecordsAge')->getLastSql();
        }
        $praise = M('MedicalRecordsPraise')->where("user_id={$user['id']} and rec_id={$condition['id']}")->find();
        //echo M('MedicalRecordsPraise')->getLastSql();
        if($praise){
            $this->praise = 0; //不能点
        }else{
            $this->praise = 1; //可以点
        }

        $this->display();
    }

    public function bl_info3_discuss(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $condition['id']=I('id');
        //$condition['addtime']=array('lt','addtime+1036800');
        $data['content']=I('content');
        $data['cashtype']=2;
        $data['distime']=time();
        $save = M('MedicalRecordsDiscuss')->where($condition)->save($data);
        if($save){
            M('MedicalRecords')->where("id={$condition['id']}")->setInc('discussnums');
            $this->reportData("discuss",1,$condition['id']);
            $discuss = M('MedicalRecordsDiscuss')->where($condition)->field('openid,rec_id')->find();
            $detail['openid']=$discuss['openid'];
            $detail['id']=$userid;
            $detail['rec_id']=$discuss['rec_id'];
            $points = M('UserOrderDetail')->where($detail)->field('fee,order_num')->find();
            $isreturn = M('UserPoints')->where("order_num = '{$points['order_num']}' AND isreturn = 0 " )->save(array('isreturn'=>1));
            if($isreturn){
                $this->userpoints(99,$discuss['openid'],1,$points['fee']/100,1,$points['order_num']);//评论完毕奖励用户金豆
            }
            $json['status']=1;
        }else{
            $json['status']=0;
            $json['msg']="点评错误";
        }
        $this->ajaxReturn($json,"JSON");
    }


    public function actity_jl(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $this->display();        
    }

    public function actity_jl_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['user_id']=$userid;
        $condition['pubtype']=1;//草稿
        $list = M('Event')->where($condition)->order('id desc')->limit($limit)->select();
        foreach ($list as $key => $value) {
            if(($value['restnums'])==0){
                $list[$key]['state']=3;//报名已满
            }else{
                $list[$key]['state']=2;//可以报名
            }
            if(strtotime($value['endtime'])<time()){
                $list[$key]['state']=1;//活动已结束
            }
        }  
        $this->ajaxReturn($list,"JSON");
    }

    public function actity_wfb_edit2(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $this->jssdk_signature();
        if(IS_POST){
            $condition['id']=I('id');
            $data['user_id']=$userid;
            $data['cashtype']=intval(I('cashtype'));
            $data['isonline']=I('isonline');
            $data['eventlink']=I('eventlink');
            $data['location']=I('location');
            $data['price']=I('price');
            $data['name']=I('name');
            $data['period']=I('period');
            $data['starttime']=I('starttime');
            $data['endtime']=I('endtime');
            $data['major']=I('major');
            $data['partitions']=I('partitions');
            $data['membercount']=I('membercount');
            $data['conditions']=I('conditions');
            $data['description']=I('description');
            $data['schedule']=I('schedule');
            $data['traffic']=I('traffic');
            $data['tips']=I('tips');
            $data['pubtype'] = I('pubtype');
            $data['restnums']=$data['membercount'];
            $searchtext = implode(" ",$data);
            $data['searchtext']=$searchtext;
            $data['savetime']=time();
            $add = M('Event')->where($condition)->save($data);
            if($add){
                $delcondition['event_id']=I('id');
                M('EventImages')->where($delcondition)->delete();
                if($image = I('images')){
                    $images = explode(",",$image);
                    for($i=0;$i<count($images);$i++){
                        $event['image']=$images[$i];
                        if($i==0){
                            M('Event')->where("id={$condition['id']}")->save(array('image'=>$event['image']));
                        }
                        $event['event_id']=I('id');
                        M('EventImages')->add($event);              
                    }
                }else{
                    $data['image'] = "./Public/static/no_pic.jpg";
                }
                
                M('EventOrganizer')->where($delcondition)->delete();
                if($organizer=I('organizers')){
                    $organizers = explode(",",$organizer);
                    for($i=0;$i<count($organizers);$i++){
                        $eventorg['name']=$organizers[$i];
                        $eventorg['event_id']=I('id');
                        M('EventOrganizer')->add($eventorg);                
                    }               
                }

                M('EventContact')->where($delcondition)->delete();
                if($contact=I('contacts')){
                    $contacts = explode(",",$contact);
                    for($i=0;$i<count($contacts)/3;$i++){
                        $eventcont['name']=$contacts[i*3+0];
                        $eventcont['mobile']=$contacts[i*3+1];
                        $eventcont['email']=$contacts[i*3+2];
                        $eventcont['event_id']=I('id');
                        M('EventContact')->add($eventcont);
                    }
                }
                $this->ajaxReturn(array('status'=>1),"JSON");exit;
            }else{
                $this->ajaxReturn(array('status'=>0),"JSON");exit;
            }
        }
        
        $condition['id']=I('id'); 
        $this->event = M('Event')->where($condition)->find();
        $this->images  = M('EventImages')->where("event_id={$condition['id']}")->select();
        $this->organizer = M('EventOrganizer')->where("event_id={$condition['id']}")->select();
        $this->contact = M('EventContact')->where("event_id={$condition['id']}")->select();
        $this->area = M('Area')->select();
        $this->major = M('Major')->select();
        $this->display();        
    }

    public function actity_wfb_delete(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $condition['id']=I('id');
        $condition['user_id']=$userid;
        $del = M('Event')->where($condition)->delete();  
        if($del){
            M('EventImages')->where("event_id={$condition['event_id']}")->delete();
            M('EventOrganizer')->where("event_id={$condition['event_id']}")->delete();
            M('EventContact')->where("event_id={$condition['event_id']}")->delete();
            $this->ajaxReturn(array('status'=>1),"JSON");

        }else{
            $this->ajaxReturn(array('status'=>1,'msg'=>'删除失败'),"JSON");
        }      
    }

    public function my_fb(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->display(); 
    }

    public function my_fb_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['pubtype']=2; 
        $condition['user_id']=$userid;
        $list = M('Event')->where($condition)->order('id desc')->limit($limit)->select();
        foreach ($list as $key => $value) {
            if(($value['restnums'])==0){
                $list[$key]['state']=3;//报名已满
            }else{
                $list[$key]['state']=2;//可以报名
            }
            if(strtotime($value['starttime'])<time()){
                $list[$key]['state']=1;//报名已结束
            }
            if(strtotime($value['endtime'])<time()){
                $list[$key]['state']=4;//活动已结束
            }  
        }            
        $this->ajaxReturn($list,"JSON");          
    }

    public function apply_people(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $this->id = I('id');
        $this->display();        
    }

    public function apply_people_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['event_id']=I('id');
        $list = M('EventRegistration')->where($condition)->select();
        $this->ajaxReturn($list,"JSON");         
    }

    public function already_apply(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->display();        
    }

    public function already_apply_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $condition['a.openid']=cookie('token');
        $list = M()->Table("box_event_registration a")->field('b.*')->join('box_event b on a.event_id = b.id')->where($condition)->limit($limit)->select();
        //echo M()->getLastSql();
        foreach ($list as $key => $value) {
            if(($value['restnums'])==0){
                $list[$key]['state']=3;//报名已满
            }else{
                $list[$key]['state']=2;//可以报名
            }
            if(strtotime($value['starttime'])<time()){
                $list[$key]['state']=1;//报名已结束
            }
            if(strtotime($value['endtime'])<time()){
                $list[$key]['state']=4;//活动已结束
            }  
        }
        $this->ajaxReturn($list,"JSON");    
    }

    public function bill_record(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->display();
    }

    public function bill_record_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $pageIndex = I('pageIndex');

        $condition['a.openid']=cookie('token');
        $condition['a.status']=2;//支付成功
        $between = $this->zdmonth($pageIndex);
        $condition['a.paytime']=array('between',array($between['stime'],$between['etime']));
        $list = M()->Table('box_user_order a')->join('box_user_order_detail b on a.order_num=b.order_num')->field("a.paytime,b.*")->where($condition)->select();
        //echo M()->getLastSql();
        $package['month'] = date('Y-m月',$between['stime']);

        foreach ($list as $key => $value) {
            switch ($value['paytype']) {
                case '1':
                    $name = M()->Table('box_medical_records a')->join('box_user b on a.user_id = b.id')->where("a.id = {$value['item_id']}")->field('b.name')->getField('name');
                    $package['list'][]=array("action"=>'单份病例','content'=>"专家：{$name} 病例编号：{$value['id']} 使用金豆:{$value['points']}","fee"=>"-{$value['fee']}","time"=>date('Y.m.d',$value['paytime']));
                    if($value['status']==3){
                        $package['list'][]=array("action"=>'病例退款','content'=>"专家：{$name} 病例编号：{$value['id']} 使用金豆:{$value['points']}","fee"=>"+{$value['fee']}");
                    }
                    break;
                case "2":
                    $name = M('User')->where("id={$value['item_id']}")->getField('name');
                    if($value['refund_id']==''){
                        $package['list'][]=array("action"=>'订阅病例','content'=>"专家：{$name} 订阅周期：{$value['nums']}月","fee"=>"-{$value['fee']}","time"=>date('Y.m.d',$value['paytime']));
                    }else{
                        $package['list'][]=array("action"=>'订阅退款','content'=>"专家：{$name}  订阅周期：{$value['nums']}月","fee"=>"+{$value['fee']}","time"=>date('Y.m.d',$value['returntime']));
                    }
                    break;
                case "3":
                    $name = M('User')->where("id={$value['item_id']}")->getField('name');
                    $package['list'][]=array("action"=>'历史病例','content'=>"专家：{$name} 使用金豆:{$value['points']}","fee"=>"-{$value['fee']}","time"=>date('Y.m.d',$value['paytime']));
                    if($value['status']==3){
                        $package['list'][]=array("action"=>'历史退款','content'=>"专家：{$name} 使用金豆:{$value['points']}","fee"=>"+{$value['fee']}","time"=>date('Y.m.d',$value['returntime']));
                    }
                    break; 
                case "4":
                    $name = M('User')->where("id={$value['item_id']}")->getField('name');
                    $package['list'][]=array("action"=>'邀请专家','content'=>"专家：{$name} 使用金豆:{$value['points']}",'points'=>"使用金豆:{$value['points']}","fee"=>"-{$value['fee']}","time"=>date('Y.m.d',$value['paytime']));
                    if($value['status']==3){
                        $package['list'][]=array("action"=>'邀请退款','content'=>"{$name}","fee"=>"+{$value['fee']}","time"=>date('Y.m.d',$value['returntime']));
                    }
                    break;
                case "5":
                    $name = M('Event')->where("id={$value['item_id']}")->getField('name');
                    $package['list'][]=array("action"=>'参加活动','content'=>"活动：{$name} 使用金豆:{$value['points']}","fee"=>"-{$value['fee']}","time"=>date('Y.m.d',$value['paytime']));
                    if($value['status']==3){
                        $package['list'][]=array("action"=>'活动退款','content'=>"活动：{$name} 使用金豆:{$value['points']}","fee"=>"+{$value['fee']}","time"=>date('Y.m.d',$value['returntime']));
                    }
                    break;
                case "6":
                    $points = $value['fee']*100;
                    $package['list'][]=array("action"=>'购买金豆','content'=>"{$points}","fee"=>"-{$value['fee']}","time"=>date('Y.m.d',$value['paytime']));
                    break;
            }
        }
        $this->ajaxReturn($package,"JSON");
    }

    public function grjd(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $user = M('User')->where("id={$userid}")->find();
        $user['headimg']=($user['image']?$user['image']:$user['headimgurl']); 
        $this->user = $user;       
        $this->display();
    }

    public function grjd_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $openid = cookie('token');
        $pageIndex = I('pageIndex');
        $pageSize = I('pageSize');
        $limit = $pageIndex*$pageSize.",".$pageSize;
        $list = M()->Table('box_user_points a')->join("box_user_points_rule b on a.type=b.id")->field('a.type,a.points,a.addtime,b.name,b.add')->where("a.openid='{$openid}' and is_frozen=1")->order('a.addtime desc')->limit($limit)->select();
        foreach ($list as $key => $value) {
            if(intval($value['add'])==2){
                $value['points']="-".$value['points'];
            }else{
                $value['points']="+".$value['points'];
            }
            $value['addtime']=date('Y.m.d',strtotime($value['addtime']));
        }
        $this->ajaxReturn($list,"JSON");
    }

    public function buy_jd(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->jssdk_signature();
        $this->id=$userid;
        $this->display();
    }

    public function service(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit; 
        $user = M('User')->where("id={$userid}")->find();
        $user['headimg']=($user['image']?$user['image']:$user['headimgurl']); 
        $this->user=$user;
        $this->display();        
    }

    public function service_page(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;  
        if(IS_POST){
            $data['content']=I('content');
            $data['addtime']=time();
            $data['user_id']=$userid;
            $add = M('Service')->add($data);
            if($add){
                $json['status']=1;
            }else{
                $json['status']=0;
            }

            $this->ajaxReturn($json,"JSON");exit;
        }
        $list = M('Service')->where("user_id={$userid}")->order('addtime desc')->limit(0,100)->select(); 
        foreach ($list as $key => $value) {
           $value['addtime']=date('Y-m-d H:i',time());
        }
        $this->ajaxReturn($list,"JSON");     
    }

    public function wxshare(){
        $condition['id']=I('id');
        $type = I('type');
        if($type==1){//病例
            $modal = "MedicalRecords";
        }else{
            $modal ="Event";
        }
        M($modal)->where($condition)->setInc('sharenums');
        $this->reportData("share",$type,$condition['id']);
        $openid= cookie('token');
        $this->userpoints(100,$openid,1,0,1);//$type,$openid,$add,$points=0,$is_frozen=1,$order_num=0
    }

    public function getVerifyCode(){
        $apikey = C('APIKEY'); //请用自己的apikey代替
        $mobile = I('mobile'); //请用自己的手机号代替
        $code = rand(100000,999999);
        $tpl_id = 2; //对应默认模板 【#company#】您的验证码是#code#
        $tpl_value = "#company#=口腔盒子&#code#=".$code;
        $sendsms =  $this->tpl_send_sms($apikey,$tpl_id, $tpl_value, $mobile);
        $result = json_decode($sendsms,true);  
        if($result['code']!=0){
            $json['msg']=$this->sms_code($result['code']);
            $json['status']=0;
        }else{
            session("smscode",$code);
            $json['status']=1;
            $json['msg']="短信发送成功"; 
        }
        //echo json_encode($json);
        $this->ajaxReturn($json,"JSON");      
    }

    private function sms_code($code){
        $errcode=array(
                        '1' => '请求参数缺失',
                        '2' => '请求参数格式错误',
                        '3' => '账户余额不足',
                        '4' => '关键词屏蔽',
                        '5' => '未找到对应id的模板',
                        '6' => '添加模板失败',
                        '7' => '模板不可用',
                        '8' => '同一手机号30秒内重复提交相同的内容',
                        '9' => '同一手机号5分钟内重复提交相同的内容超过3次',
                        '10' => '手机号黑名单过滤',
                        '11' => '接口不支持GET方式调用',
                        '12' => '接口不支持POST方式调用',
                        '13' => '营销短信暂停发送',
                        '14' => '解码失败',
                        '15' => '签名不匹配',
                        '16' => '签名格式不正确',
                        '17' => '24小时内同一手机号发送次数超过限制',
                        '-1' => '非法的apikey',
                        '-2' => 'API没有权限',
                        '-3' => 'IP没有权限',
                        '-4' => '访问次数超限',
                        '-5' => '访问频率超限',
                        '-50' => '未知异常',
                        '-51' => '系统繁忙',
                        '-52' => '充值失败',
                        '-53' => '提交短信失败',
                        '-54' => '记录已存在',
                        '-55' => '记录不存在',
                        '-57' => '用户开通过固定签名功能，但签名未设置',
                        );
        return $errcode["{$code}"];
    }

    /**
    * 模板接口发短信
    * apikey 为云片分配的apikey
    * tpl_id 为模板id
    * tpl_value 为模板值
    * mobile 为接受短信的手机号
    */
    private function tpl_send_sms($apikey, $tpl_id, $tpl_value, $mobile){
        $url="http://yunpian.com/v1/sms/tpl_send.json";
        $encoded_tpl_value = urlencode("$tpl_value");  //tpl_value需整体转义
        $post_string="apikey=$apikey&tpl_id=$tpl_id&tpl_value=$encoded_tpl_value&mobile=$mobile";
        return $this->sock_post($url, $post_string);
    }

    /**
    * url 为服务的url地址
    * query 为请求串
    */
    private function sock_post($url,$query){
        $data = "";
        $info=parse_url($url);
        $fp=fsockopen($info["host"],80,$errno,$errstr,30);
        if(!$fp){
            return $data;
        }
        $head="POST ".$info['path']." HTTP/1.0\r\n";
        $head.="Host: ".$info['host']."\r\n";
        $head.="Referer: http://".$info['host'].$info['path']."\r\n";
        $head.="Content-type: application/x-www-form-urlencoded\r\n";
        $head.="Content-Length: ".strlen(trim($query))."\r\n";
        $head.="\r\n";
        $head.=trim($query);
        $write=fputs($fp,$head);
        $header = "";
        while ($str = trim(fgets($fp,4096))) {
            $header.=$str;
        }
        while (!feof($fp)) {
            $data .= fgets($fp,4096);
        }
        return $data;
    }

    private function snsauth(){
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".C('WX_APPID')."&redirect_uri=".urlencode(C('WX_BACK_URL'))."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header("Location:".$url); 
        exit;         
    }

    private function saveMedia($mediaid){
        $access_token=$this->getAccessToken();
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$mediaid;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //对body进行输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
       
        curl_close($ch);
        $media = array_merge(array('mediaBody' => $package), $httpinfo);
        
        //求出文件格式
        preg_match('/\w\/(\w+)/i', $media["content_type"], $extmatches);
        $fileExt = $extmatches[1];
        $filename = guid().".{$fileExt}";
        $dirname = "Public/Uploads/Media/".date('Ymd')."/";
        if(!file_exists($dirname)){
            mkdir($dirname,0777,true);
        }
        $save = file_put_contents($dirname.$filename,$media['mediaBody']);
        if($save){
            // import('ORG.Util.Image.ThinkImage');
            // $img = new ThinkImage(THINKIMAGE_GD, $dirname.$filename); 
            // $img->thumb(320, 504,THINKIMAGE_THUMB_FIXED)->save($dirname.$filename);
        }
        return $dirname.$filename;
    }

    public function editMedia(){
        $mediaid = I('mediaid');
        $access_token=$this->getAccessToken();
        $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$mediaid;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //对body进行输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
       
        curl_close($ch);
        $media = array_merge(array('mediaBody' => $package), $httpinfo);
        
        //求出文件格式
        preg_match('/\w\/(\w+)/i', $media["content_type"], $extmatches);
        $fileExt = $extmatches[1];
        $filename = guid().".{$fileExt}";
        $dirname = "Public/Uploads/Media/".date('Ymd')."/";
        if(!file_exists($dirname)){
            mkdir($dirname,0777,true);
        }
        $save = file_put_contents($dirname.$filename,$media['mediaBody']);
        if($save){
        }
        $this->ajaxReturn(array('image'=>$dirname.$filename),"JSON");
    }

    public function callback(){
        cookie('token',null);
        if(!isset($_GET['code'])){
            echo "";exit;
        }
        $code = I("code");
        // @exec('php /data/www/grownup.ciaoke.com/getsnstoken.php '.$code, $output);
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx33c4a57e70c5720a&secret=350d7c541f4f1e401197dbaeb8798dee&code='.$code.'&grant_type=authorization_code';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $token_data = curl_exec($ch);
        curl_close($ch);
        //echo $token_data;
        //
        $token_json = json_decode($token_data);
        $openid = $token_json->openid;
        $access_token = $token_json->access_token;
        //@exec('php /data/www/grownup.ciaoke.com/getuser.php '.$access_token.' '.$openid, $output2);
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $user = curl_exec($ch);
        curl_close($ch);
        $user = json_decode($user);
        if(!$user->errcode){
            #用户基本信息
            $data['openid'] = $openid;
            $data['nickname'] = $user->nickname;
            $data['nickname'] = base64_encode($data['nickname']);
            $data['sex'] = $user->sex;
            $data['province'] = $user->province;
            $data['city'] = $user->city;
            $data['country'] = $user->country;
            $data['headimgurl'] = $user->headimgurl;
            $created = date("Y-m-d H:i:s");
            $token = guid();

            //绑定判断

            $state = I('state');

            if("STATE"==$state){
                $sql = "INSERT INTO `box_user` (`openid`,`nickname`,`sex`,`province`,`city`,`country`,`headimgurl`,`token`) 
                        VALUES ('".$data['openid']."','".$data['nickname']."',".$data['sex'].",'".$data['province']."','".$data['city']."','".$data['country']."','".$data['headimgurl']."','".$token."') 
                        ON DUPLICATE KEY 
                        UPDATE `nickname`='".$data['nickname']."',`province`='".$data['province']."',`city`='".$data['city']."',
                                `country`='".$data['country']."',`headimgurl`='".$data['headimgurl']."',`created`='".$created."';";
                //`sex`=".$data['sex'].",
                $result = M()->query($sql); 
                $result = mysql_affected_rows();
            }elseif($state){
                $condition['token']=$state;
                $condition['openid']=array('eq','');//没有绑定过OPENID
                $save = M('User')->where($condition)->save($data);
                if($save){
                    $result=1;
                }else{
                    $result=0;
                }
            }
            if(!$result){
                echo "<h1>微信授权失败,请重试</h1>";
                cookie('token',null);
                exit();
            }else{
                //新注册和绑定更新注册时间
                $reg = $this->updatetime($result,$openid);
                //更新当前登录日期
                $login = $this->updatelogin($openid);
                //只当日第一登录增加登录金豆
                (1==$login) && ($this->userpoints(1,$openid,1,0,1)); 
                //设置cookie
                cookie('token',$openid);
                usleep(100);
                $this->searchtext($openid);
                $this->redirect('/Index');
            }
        }else{
            echo "<h1>微信授权失败,请重试</h1>";
            cookie('token',null);
            exit();
        }
    }
    /**
     * @param type 金豆规则中的类型ID
     * @param openid 当前用户的微信ID
     * @param add 1标示为增加金豆2标示为减少金豆
     * @param points 手动金豆数
     * @param is_frozen 是否冻结金豆
     * @param order_num 订单号
     */
    private function userpoints($type,$openid,$add,$points=0,$is_frozen=1,$order_num=0){
        $data['openid']=$openid;
        if(!$points){
            $data['points'] = M('UserPointsRule')->where("id={$type}")->getField('points');//获得金豆规则对应的金豆 
        }else{
            $data['points'] = $points;
        }
        $data['is_frozen']=$is_frozen;
        $data['order_num']=$order_num;
        $data['type']=$type;
        $points = M('UserPoints')->add($data);//插入金豆详细
        if(($add==1) && ($is_frozen==1)){//金豆不冻结
            M('User')->where("openid='{$openid}'")->setInc('points',$data['points']);//更新用户全局金豆
            return 1;
        }elseif(($add!=1)){
            $isDec = M('User')->where("openid='{$openid}' AND points >= " . $data['points'])->setDec('points',$data['points']);
            return $isDec;
        }
    }

    private function updatetime($result,$openid){
        if($result == 1){
            $regid['openid']=$openid;
            $regtime['regtime']=date("Y-m-d H:i:s");
            $save = M('User')->where($regid)->save($regtime);
        }        
    }

    private function updatelogin($openid){
        $checkin = date("Y-m-d");
        $created = date("Y-m-d H:i:s");
        $token = md5($openid."|".$checkin);
        $sql = "INSERT INTO `box_user_login_record`(`openid`, `checkin`, `token`, `created`) VALUES ('{$openid}','{$checkin}','{$token}','{$created}') ON DUPLICATE KEY UPDATE `created`='{$created}';";
        M()->query($sql);
        return mysql_affected_rows();
    }

    private function updatediscuss($openid){
        $checkin = date("Y-m-d");
        $created = date("Y-m-d H:i:s");
        $token = md5($openid."|".$checkin);
        $sql = "INSERT INTO `box_user_discuss_record`(`openid`, `checkin`, `token`, `created`) VALUES ('{$openid}','{$checkin}','{$token}','{$created}') ON DUPLICATE KEY UPDATE `created`='{$created}';";
        M()->query($sql);
        return mysql_affected_rows();
    }

    private function updateExpertPub($userid){
        $pubdate = date("Y-m-d");
        $token = md5($userid."|".$pubdate);
        $sql = "INSERT INTO `box_expert_pub_record`(`user_id`, `pubdate`, `token`) VALUES ('{$userid}','{$pubdate}','{$token}') ON DUPLICATE KEY UPDATE `pubnums`=`pubnums`+1;";
        M()->query($sql);
        return mysql_affected_rows();        
    }

    private function searchtext($openid){
        $profile = M('User')->where("openid='{$openid}'")->find();
        $profile['nickname']=base64_decode($profile['nickname']);
        unset($profile['searchtext']);
        $data['searchtext'] = implode(' ',$profile);
        M('User')->where("openid='{$openid}'")->save($data);
    }

    //扣除金豆
    private function jdPay($data) {       
        switch ($data['paytype']) {
            case '1':
                $type = "2";
                break;
            case '2':
                $type = "4";
                break;
            case '3':
                $type = "5";
                break;
            case '4':
                $type = "6";
                break;
            case '5':
                $type = "3";
                break;
        }
        
        $openid = cookie('token');
        $decPoints = $this->userpoints($type,$openid,2,$data['points'],1,$data['order_num']);//($type,$openid,$add,$points=0,$is_frozen,$order_num=0){
        if(!$decPoints){
            return false;
        }
        
        return true;
    }
    
    //金豆抵扣逻辑
    public function allpoints(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $condition['order_num'] = I('order_num');
        $check = M('UserOrder')->where($condition)->find();
        $json['status']=0;
        if($check['points'] > 0) {
            if ($this->jdPay($check)) {
                if($check['allpoints']==2){
                    $orderstatus = M('UserOrder')->where('status<>2')->save(array('status'=>2,'paytime'=>time()));
                    if($orderstatus){//必须有改动
                        $json['status']=1;
                        $openid=cookie('token');
                        $pubtype=$check['paytype'];
                        $addtime = time();
                        if($pubtype==1){
                            $item_id = M('UserOrderDetail')->where($condition)->getField('item_id');
                            $token = md5($openid."|".$item_id);
                            $sql = "INSERT INTO `box_user_records`(`openid`, `rec_id`, `expert_id`, `token`, `addtime`)
                            VALUES ('{$openid}',{$item_id},{$userid},'{$token}',{$addtime})
                            ON DUPLICATE KEY UPDATE `addtime`={$addtime}";
                            M()->query($sql);
                        }elseif($pubtype==2){
                            //订阅下个月的，这里不做处理
                        }elseif($pubtype==3){
                            $expert = D('PackageView')->where($condition)->find();
                            $d = new DateTime($expert['packageend']);
                            $d->modify( '+1 day' );
                            $time = $d->format( 'Y-m-d' );
                            $recoder['pubtime']=array("lt",strtotime($time));//小于下一天的0点
                            $recoder['user_id']=$expert['item_id'];
                            $recoder['pubtype']=2;//已经发布的
                            $recoder['cashtype']=2;//收费的
                            $list = M('MedicalRecords')->field('id')->where($recoder)->select();//获取该专家截至日期前的所有简历
                            foreach ($list as $key => $value) {
                                $addtime = time();
                                $token = md5($openid."|".$value['id']);
                                $sql = "INSERT INTO `box_user_records`(`openid`, `rec_id`, `expert_id`, `token`, `addtime`)
                                VALUES ('{$openid}',{$value['id']},{$expert['item_id']},'{$token}',{$addtime})
                                ON DUPLICATE KEY UPDATE `addtime`={$addtime}";
                                M()->query($sql);
                            }
                        }elseif($pubtype==4){
                            $list = M('UserOrderDetail')->where($condition)->select();
                            foreach ($list as $key => $value) {
                                $record['rec_id']=$value['rec_id'];
                                $record['user_id']=$value['item_id'];
                                $record['pubtype']=$value['pubtype'];
                                $record['cashtype']=3;//邀请中
                                $record['addtime']=time();
                                $record['openid']=$openid;//付费人的openid
                                $record['content']='';//占坑没内容
                                $record['order_num']=$condition['order_num'];
                                $record['price']=$check['points']/100;
                                M('MedicalRecordsDiscuss')->add($record);
                            }
                        }elseif($pubtype == 5){
                            $list = M('UserOrderDetail')->where($condition)->find();
                            $event['event_id']=$list['item_id'];//活动ID
                            $event['openid']=$openid;
                            $event['name']=$list['name'];
                            $event['mobile']=$list['mobile'];
                            $event['hospital']=$list['hospital'];
                            $event['department']=$list['department'];
                            $event['nums']=$list['nums'];
                            $event['isallpoint']=2;
                            $restnums = M('Event')->where("id={$list['item_id']}")->getField('restnums');
                            if($restnums - $list['nums'] >= 0 ) {
                                $add = M('EventRegistration')->add($event);//已经支付，已经用全部金豆支付
                                $dec = M('Event')->where("id={$list['item_id']} and restnums > 0")->setDec('restnums',$list['nums']);
                            } else {
                                $json['status']=1;
                            }
                        }
                    }
                } else {
                    $json['status']=1;
                }
            }
        }

        $this->ajaxReturn($json,"JSON");
    }

    //返还金豆/支付金豆冻结/失败后返还金豆/只限于微信支付正常失败
    public function backpoints(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $openid=cookie('token');
        $type=I('type');
        $order_num = I('order_num');
        if($type==1){
            $condition['order_num']=$order_num;
        }else{
            $condition['order_num']=M('UserOrder')->where("prepay_id='{$order_num}'")->getField('order_num');
        }

        $condition['openid']=$openid;
        $condition['isreturn']=array('eq',1);
        $records = M('UserPoints')->where($condition)->find();
        if ($records) {
            $json['status']=0;
        } else {
            $condition['isreturn']=array('neq',1);
            $records = M('UserPoints')->where($condition)->find();
            if (!$records) {
                $json['status']=0;
            } else {
                $points = $records['points'];
                $save = M('UserPoints')->where($condition)->save(array('isreturn'=>1));
                if($save){
                    $this->userpoints(99,$openid,1,$points,1,$condition['order_num']);//$type,$openid,$add,$points=0,$is_frozen=1,$order_num=0
                    $paytype = M('UserOrder')->where("order_num='{$order_num}'")->getField('paytype');
                    if($paytype==5){
                        $eventid = M('UserOrderDetail')->where("order_num='{$order_num}'")->getField('item_id');
                        $nums = M('UserOrderDetail')->where("order_num='{$order_num}'")->getField('nums');
                        M('EventRegistration')->where("openid='{$openid}' and event_id={$eventid}")->delete();//删除报名信息
                        M('UserOrderDetail')->where("order_num='{$order_num}'")->delete();
                        M('UserOrder')->where("order_num='{$order_num}'")->delete();
                        M('Event')->where("id={$eventid}")->setInc('restnums',$nums);
                    }
                    $json['status']=1;
                }else{
                    $json['status']=0;
                }
            }
        }
       
        $this->ajaxReturn($json,"JSON");
    }

    /**
     * 微信支付部分
     */

    public function wxPay(){
        !cookie('token') && $this->snsauth();
        $userid=M('User')->where("openid='".cookie('token')."'")->getField('id');
        !$userid && $this->snsauth() && exit;
        $this->appid = C('WX_APPID');
        $this->nonceStr = $_POST["nonceStr"];
        $this->timestamp = $_POST["timestamp"];
        $this->signature = $_POST["signature"];
        $getdetail = $_POST['detail'];
        $this->paytype = $paytype = I('paytype');
        $this->totalfee = I('totalfee');//把圆变成分
        $totalfee = I('totalfee')*100;
        $this->points = $points=I('points');
        if ($points < 0 || $totalfee < 0) {
            $this->show('<script>alert("创建订单失败");</script>');exit;
        }
        
        $this->div_name=I('tips');
        $this->expertname = I('expertname');
        //
        //DEMO DATA
        //<=====================================================>
        // $paytype=1;//单份病例
        // $getdetail='[{"id":1,"fee":100,"points":100}]';//病例ID
        // $totalfee=100;
        // $points=100;
        //<=====================================================>
        // $paytype=2;//订阅整月病例
        // $getdetail='[{"id":1,"fee":100,"points":100,"limit":4}]';//专家的ID LIMIT：订阅多少个月
        // $totalfee=100;
        // $points=100;
        //<=====================================================>
        // $paytype=3;//订阅打包病例
        // $getdetail='[{"id":1,"fee":100,"points":100}]';//专家的ID
        // $totalfee=100;
        // $points=100;
        //<=====================================================>
        // $paytype=4;//邀请专家评论
        // $getdetail='[{"id":1,"fee":100,"points":100,"pubtype":1,"rec_id":1}]';//专家的ID rec_id 病例的ID
        // $totalfee=100;
        // $points=100;
        //<=====================================================>
        // $paytype=5;//参加活动付费
        // $getdetail='[{"id":1,"fee":100,"points":100,"name":"张三","hospital":"医院","department":"科室","mobile":"13777777777","nums":"2"}]';//活动的ID
        // $totalfee=100;
        // $points=100;
        //<=====================================================>
        // $paytype=6;//购买金豆
        // $getdetail='[{"id":1,"fee":100,"points":0}]';//当前用户的ID
        // $totalfee=100;
        // $points=0;
        //<=====================================================>                     
        //获取对应的表
        $modal=$this->getModal($paytype);
        //解析JSON数组
        $details = json_decode($getdetail,true);

        $this->eventid = 0;
        
        //组合订单详情
        foreach ($details as $key => $value) {
            if($paytype == 4){
                $discuss['rec_id']=$value['rec_id'];
                $discuss['user_id']=$value['id'];
                $discuss['content']=array("eq",'');
                $check = M('MedicalRecordsDiscuss')->where($discuss)->find();
                if($check){
                    echo "邀请专家中存在已邀请专家";
                    exit;
                }
            } else if ($paytype == 5) {
                $this->eventid = $value['id'];
                $condition['openid']=cookie('token');
                $condition['item_id']=$value['id'];
                $isRegistration= M('EventRegistration')->where("openid={$condition['openid']} and event_id={$condition['item_id']}")->find();
                $isOrdered = M('UserOrderDetail')->where($condition)->find();
                if(!$isRegistration && $isOrdered){
                    M('UserOrderDetail')->where($condition)->delete();
                }
            }

            ($paytype>1)?($name = M($modal)->where("id={$value['id']}")->getField("name")):$name="病例";
            ($paytype==6) && $name="金豆";
            $detail[]=array("paytype"=>$paytype,"fee"=>$value['fee'],"points"=>$value['points'],"item_id"=>$value['id'],"item_name"=>$name,
                "limit"=>$value['limit'],
                "pubtype"=>$value['pubtype'],"rec_id"=>$value['rec_id'],
                'name'=>$value['name'],'mobile'=>$value['mobile'],'hospital'=>$value['hospital'],'department'=>$value['department'],'nums'=>$value['nums'],
                );
        }

        $this->order_num = date("YmdHis").rand(100000,999999);//订单号
        if(0 == $totalfee){//全部金豆支付
            $this->needCash = 0;//不需要调用在线支付
            $allpoints = 2;//全部用金豆支付
            $order_num = $this->wxcreatOrder($this->order_num, $userid,$paytype,$totalfee,$points,$detail,$allpoints);//获取订单号
            if(empty($order_num)){
                $this->show('<script>alert("创建订单失败");</script>');exit;
            }            
        }else{
            $this->needCash = 1;//需要调用在线支付
            //<-- 需要用到微信支付部分开始 -->
            $this->prepay_id = $prepay_id = $this->wxcreatOrder($this->order_num, $userid,$paytype,$totalfee,$points,$detail);
            if(empty($prepay_id)){
                $this->show('<script>alert("创建订单失败");</script>');exit;
            }
            
            $sign['appId']=C('WX_APPID');
            $sign['timeStamp']=$this->timestamp;
            $sign['package']="prepay_id={$this->prepay_id}";
            $sign['nonceStr']=$this->nonceStr;
            $sign['signType']="MD5";
            $this->paySign = $this->wxpaySign($sign);
            //<-- 需要用到微信支付部分结束-->            
        }

        $this->display();
    }

    private function getModal($paytype){
        switch ($paytype) {
            case '1':
                $modal = "MedicalRecords";
                break;
            case '2':
                $modal = "User";
                break;
            case '3':
                $modal = "User";
                break;
            case '4':
                $modal = "User";
                break;
            case '5':
                $modal = "Event";
                break;
        }
        return $modal;
    }
    /**
     * wxcreatOrder创建订单
     * @access private
     * @param userid 用户ID
     * @param paytype 当前支付的种类
     * @param totalfee 总共支付的金额
     * @param points 使用的金豆
     * @param detail 订单详情 array(id,fee,points,substime,subetime,pubtype)
     * @param allpoints 是否用全部金豆支付
     */
    private function wxcreatOrder($order_num, $userid,$paytype,$totalfee,$points,$detail,$allpoints=1){//创建订单
        M()->startTrans();//需要回滚
        $data['user_id']=$userid;
        $data['paytype']=$paytype;
        $data['totalfee']=$totalfee;
        $data['points']=$points;
        $data['order_num']=$order_num;//订单号
        $data['addtime']=time();
        $data['endtime']=$data['addtime']+3600;//1小时过期
        $data['openid']=cookie('token');
        $data['status']=3;//支付的时候直接赋予支付状态为失败等待微信通知

        if($allpoints==1){//微信支付
            if($prepay = $this->wxgetPrepay($data['order_num'],$totalfee,$points,$paytype,$data['addtime'],$data['endtime'],$detail)){
                $data['prepay_id']=$prepay;
            } else {
                echo "获取prepay_id错误";
                return 0;
            }
        } else {//全部金豆支付
            $data['allpoints']=2;
            $prepay=$data['order_num'];
        }

        $add = M('UserOrder')->add($data);
        if(!$add){
            M()->rollback();
            echo "创建用户订单错误";
            return 0;
        }
        foreach ($detail as $key => $value) {
            $detail['order_num'] = $data['order_num'];
            $detail['openid'] = cookie('token');
            $detail['paytype']=$paytype;
            $detail['fee']= $totalfee;
            $detail['points']=$value['points'];
            $detail['item_id']=$value['item_id'];
            $detail['return_num']="RE{$data['order_num']}".rand(1000,9999);
            if($paytype==2){//订阅有订阅周期
                $SEtime= $this->getSEtime($value['limit']);
                $detail['substime']=$SEtime['substime'];
                $detail['subetime']=$SEtime['subetime'];
            }
            if($paytype == 4){//邀请有公开不公开以及病例ID
                $detail['pubtype']=$value['pubtype'];
                $detail['rec_id']=$value['rec_id'];
            }
            if($paytype==5){
                $detail['name']=$value['name'];
                $detail['mobile']=$value['mobile'];
                $detail['hospital']=$value['hospital'];
                $detail['department']=$value['department'];
                $detail['nums']=$value['nums'];

            }
            $add = M('UserOrderDetail')->add($detail);

            if(!$add){
                M()->rollback();
                echo "添加详细错误";
                return 0;
            }
        }
        M()->commit();
        return $prepay;
    }

    private function wxgetPrepay($order_num,$totalfee,$points,$paytype,$time_start,$time_expire,$detail){//获取预支付ID
        $param['appid']=C('WX_APPID');//APPID 
        $param['mch_id']=C('WX_MCHID');//商户号
        $param['device_info']="WEB";//注意：PC网页或公众号内支付请传"WEB"  
        $param['nonce_str']=$this->nonceStr;//随机数
        $param['body']=$this->wxpayType($paytype);//商品或支付单简要描述 
        $param['detail']="口腔盒子相关支付";
        $param['attach']=$points;//这里存放使用的金豆数，附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        $param['out_trade_no']=$order_num;//商户系统内部的订单号
        $param['fee_type']="CNY";//符合ISO 4217标准的三位字母代码，默认人民币：CNY
        $param['total_fee']=$totalfee;//订单总金额，只能为整数，交易金额默认为人民币交易，接口中参数支付金额单位为【分】，
        $param['spbill_create_ip']=get_client_ip();//APP和网页支付提交用户端ip
        $param['time_start']=date("YmdHis",$time_start);
        $param['time_expire']=date("YmdHis",$time_expire);
        //$param['goods_tag']=$goods_tag;//商品标记，代金券或立减优惠功能的参数
        $param['notify_url']=C('WX_NOTIFY');//接收微信支付异步通知回调地址
        $param['trade_type']="JSAPI"; //交易类型 
        //$param['product_id']=$product_id;//trade_type=NATIVE，此参数必传。此id为二维码中包含的商品ID，商户自行定义。
        $param['openid']=cookie('token');
        $param['sign'] = $this->wxpaySign($param);//支付签名

        $data = $this->wxPrepayXML($param);
        if($response = $this->postData($data)){
            $xml = (array) simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA);//XML转数组，还要再验证一次签名
            if( ($xml['return_code']=="SUCCESS") && ($xml['result_code']=="SUCCESS")){
                $wxPrepaySign = $xml['sign'];
                //去除返回的签名
                unset($xml['sign']);
                //
                
                if($wxPrepaySign==$this->wxpaySign($xml)){
                    return $xml['prepay_id'];
                }else{
                    return 0;
                }
            }elseif($xml['err_code']=='SYSTEMERROR'){//微信支付其实也会抽风的
                $this->show('<script>alert("微信支付网关出错，请稍后再试！");</script>');
                exit;
            }else{
                return 0 ;
            }        
        }else{
            return 0;
        }

    }

    private function wxPrepayXML($params){
        $xml="<xml>";
        foreach ($params as $key => $value) {
            $xml .= "<{$key}>$value</{$key}>";
        }
        $xml .="</xml>";
        return $xml;
    }

    private function postData($data){
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1 );
        curl_setopt($ch, CURLOPT_HEADER, 0 );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data );
        $response = curl_exec($ch);
        //print_r($response);
        curl_close($ch);
        if(!$response){
            return 0;
        }
        
        return $response;   
    }

    /**
     * Detail
     * @type array()
     * @param paytype 类型
     * @param fee
     * @param points 金豆
     * @param item_name
     * @param item_id
     * @condition TYPE == 2
     * @param substime 订阅开始时间 
     * @param subetime 订阅结束时间
     * 
     */
    private function wxpayDetail($paytype,$detail){
        $msg = $this->wxpayType($paytype);
        foreach ($detail as $key => $value) {
            $msg .= "消费：{$value['fee']} 元/金豆：{$value['points']}/项目：{$msg} 目标:{$value['item_name']}(序号：{$value['item_id']})/";
            if($paytype==2){
                $msg.="订阅周期:".date("Y-m-d",$value['substime'])."至".date("Y-m-d",$value['subetime'])."/";
            }
        }
        return $msg;
    }

    private function wxpayType($paytype){
      switch ($paytype) {
          case '1':
              $body="购买单份专家病例";
              break;
          case '2':
              $body="购买订阅专家病例";
              break;
          case '3':
              $body="打包购买专家病例";
              break;
          case '4':
              $body="付费邀请专家评论";
              break;
          case '5':
              $body="付费参加活动";
              break;
          case '6':
              $body="购买金豆";
              break;
          default:
              $body="口腔盒子相关支付";
              break;
      }

      return $body;
    }

    private function wxpaySign($param){//微信支付签名（微信支付需要用到3次该方法）
        ksort($param,SORT_STRING);
        foreach ($param as $key => $value) {
            if ($value != '')
                $stringA[]="{$key}={$value}";
        }
        
        $stringA=implode("&",$stringA);
        $key=C('WX_APIKEY');
        $stringSignTemp="{$stringA}&key={$key}";
        $paySign = strtoupper(md5($stringSignTemp));
        return $paySign;

    }
    
    private function wxRefundXML($params){
        $xml="<xml>";
        foreach ($params as $key => $value) {
            $xml .= "<{$key}>$value</{$key}>";
        }
        $xml .="</xml>";
        return $xml;
    }

    private function postXmlCurl($xml,$second = 30)
    {      
        $url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        //初始化curl        
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,TRUE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT, "./Cert/apiclient_cert.pem");
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY, "./Cert/apiclient_key.pem");

        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        }else{
            return 0;
        }
    }
    private function getSEtime($limit){//计算订阅周期
        $d = $c = new DateTime();
        $d->modify( 'first day of next month' );
        $stime = $d->format( 'Y-m-d' );

        $c->modify( "first day of +{$limit} month" );
        $etime = $c->format( 'Y-m-d' );

        return array("substime"=>strtotime($stime),"subetime"=>strtotime($etime)-1);
    }

    private function getThisMonth(){
        $d = $c = new DateTime();
        $d->modify( 'first day of this month' );
        $stime = $d->format( 'Y-m-d' );

        $c->modify( "first day of next month" );
        $etime = $c->format( 'Y-m-d' );

        return array("substime"=>strtotime($stime),"subetime"=>strtotime($etime)-1);        
    }

    private function zdmonth($limit){
        $d = $c = new DateTime();
        $d->modify( "first day of -{$limit} month" );
        $stime = $d->format( 'Y-m-d' );
        $stimes= strtotime($stime);

        $c->modify( 'last day of -0 month' );
        $etime = $d->format( 'Y-m-d' );
        $etimes= strtotime($etime)+86399;

        return array('stime'=>$stimes,'etime'=>$etimes);
    }

    private function reportData($modal,$type,$item_id){
        $table = "box_report_".$modal;
        $addtime = date("Y-m-d");
        $token = md5("{$type}|{$item_id}|{$addtime}");
        $sql = "INSERT INTO `{$table}` (`type`, `item_id`, `token`, `addtime`) VALUES ({$type},{$item_id},'{$token}','{$addtime}') ON DUPLICATE KEY UPDATE `nums`=`nums`+1;";
        M()->query($sql);
    }
}